<?php

use Drupal\shusy_product\Entity\ShusyProduct;
use Drupal\shusy_product\Entity\ShusyProductComment;
use Drupal\shusy_product\Entity\ShusyProductStandard;
use Drupal\shusy_product_standards\Entity\ShusyProductStandards;

function shusy_product_shusy_product_entity_form($form, &$form_state, ShusyProduct $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProduct::class] = $e;


  $form['name'] = [
    '#type' => 'textfield',
    '#title' => t('产品标题'),
    '#required' => TRUE,
    '#default_value' => $e->name,
    '#element_validate' => ['shusy_product_validate_title_length'],
    '#size' => 128,
    '#maxlength' => 255,
  ];
  $form['info'] = [
    '#type' => 'textfield',
    '#title' => t('产品说明'),
    '#required' => TRUE,
    '#default_value' => $e->info,
  ];
  $form['vip'] = [
    '#type' => 'checkbox',
    '#title' => t('允许VIP折扣'),
    '#default_value' => $e->vip,
    '#description' => t('仅当产品属于VIP价格分类时有效'),
  ];
  $form['summary'] = [
    '#type' => 'textarea',
    '#title' => t('摘要介绍'),
    '#default_value' => $e->summary,
  ];

  if (module_exists('shusy_product_standards')) {
    //启用多规格
    if (empty($form_state['multistandards']) && empty($form_state['multistandardsDel'])) {
      $multistandards = shusy_product_standards_load_multiple(FALSE, [
        'product_id' => $e->id,
      ]);
      if (!empty($multistandards)) {
        $form_state['multistandards'] = array_values($multistandards);
      }
      else {
        $form_state['multistandards'] = [];
      }
    }
    $form['multistandards'] = [
      '#title' => t('多规格'),
      '#type' => 'fieldset',
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#tree' => TRUE,
      '#prefix' => "<div id='multistandards-form-wrapper'>",
      '#suffix' => '</div>',
    ];
    $form['multistandards']['items'] = [
      '#type' => 'item',
      '#theme' => 'shusy_product_form_multistandards',
    ];
    $parents = [];
    foreach ($form_state['multistandards'] as $pi => $standard) {
      if ($standard instanceof ShusyProductStandards) {
        $standardId = "multistandards-form-wrapper-{$pi}";
        $form['multistandards']['items'][$pi] = [
          '#type' => 'container',
          '#entity_builders' => ['shusy_product_form_build_entity'],
          '#parents' => array_merge($parents, ['multistandards'], ['items'], [$pi]),
        ];
        $form['multistandards']['items'][$pi]['id'] = [
          '#type' => 'value',
          '#value' => $standard->id,
          '#parents' => array_merge($parents, ['multistandards'], ['items'], [$pi], ['id']),
        ];
        $form['multistandards']['items'][$pi]['standard'] = [
          '#type' => 'textfield',
          '#title' => t('规格'),
          '#title_display' => 'invisible',
          '#default_value' => $standard->standard,
          '#required' => TRUE,
          '#size' => 32,
          '#parents' => array_merge($parents, ['multistandards'], ['items'], [$pi], ['standard']),
        ];
        $form['multistandards']['items'][$pi]['status'] = [
          '#type' => 'checkbox',
          '#title' => t('启用'),
          '#title_display' => 'invisible',
          '#default_value' => $standard->status,
          '#parents' => array_merge($parents, ['multistandards'], ['items'], [$pi], ['status']),
        ];
        $form['multistandards']['items'][$pi]['delete'] = [
          '#type' => 'submit',
          '#value' => t('删除'),
          '#submit' => ['shusy_product_form_multistandards_remove_submit'],
          '#name' => "$standardId-op-del",
          '#limit_validation_errors' => [],
          '#ajax' => [
            'callback' => 'shusy_product_form_multistandards_callback',
            'wrapper' => 'multistandards-form-wrapper',
          ],
          '#parents' => array_merge($parents, ['multistandards'], ['items'], [$pi], ['delete']),
        ];
      }
    }
    $form['multistandards']['add'] = [
      '#type' => 'submit',
      '#value' => t('添加规格'),
      '#submit' => ['shusy_product_form_multistandards_add_submit'],
      '#limit_validation_errors' => [],
      '#ajax' => [
        'callback' => 'shusy_product_form_multistandards_callback',
        'wrapper' => 'multistandards-form-wrapper',
      ],
    ];
  }
  if (!empty($e->id)) {
    $form['status'] = [
      '#type' => 'checkbox',
      '#title' => t('上架'),
      '#default_value' => $e->status,
      '#element_validate' => ['shusy_product_validate_status'],
    ];
  }

  //  $form['status'] = [
  //    '#type' => 'select',
  //    '#title' => t('状态'),
  //    '#options' => $e->getStatusOptions(),
  //    '#default_value' => $e->status,
  //    '#chosen' => TRUE,
  //    '#required' => TRUE,
  //  ];


  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function shusy_product_form_multistandards_remove_submit($form, &$form_state) {
  [, , $li] = $form_state['triggering_element']['#array_parents'];
  $item = $form_state['multistandards'][$li];
  $form_state['multistandardsDel'][] = $item;
  unset($form_state['multistandards'][$li]);
  $form_state['rebuild'] = TRUE;
}

function shusy_product_form_multistandards_add_submit($form, &$form_state) {
  $form_state['multistandards'][] = new ShusyProductStandards();
  $form_state['rebuild'] = TRUE;
}

function shusy_product_form_multistandards_callback($form, &$form_state) {
  return $form['multistandards'];
}

function theme_shusy_product_form_multistandards($variables) {
  $output = '';
  $form = $variables['form'];
  $rows = [];

  foreach (element_children($form) as $id) {
    $form[$id]['sort']['#attributes']['class'] = ['item-weight'];
    $rows[] = [
      'data' => [
        drupal_render($form[$id]['standard']),
        drupal_render($form[$id]['status']),
        drupal_render($form[$id]['delete']),
      ],
      'class' => ['draggable'],
    ];
  }
  $header = [
    t('规格'),
    t('启用'),
    t('操作'),
  ];

  $table_id = 'items-table';
  $form['items_markup']['markup']['#markup'] = theme('table', [
    'header' => $header,
    'rows' => $rows,
    'attributes' => ['id' => $table_id],
  ]);
  $output .= drupal_render_children($form);
  return $output;
}

function shusy_product_validate_title_length($element, &$form_state) {
  $value = $element['#value'];
  if (mb_strlen($value) > 255) {
    form_error($element, t('%name 不能超过255个字符.', ['%name' => $element['#title']]));
  }
}

//检查产品状态 必须有上架的规格 产品才能上架
function shusy_product_validate_status($element, &$form_state) {
  $p = $form_state[ShusyProduct::class];
  if ($p instanceof ShusyProduct) {
    $value = $element['#value'];
    if ($value == 1) {
      $es = shusy_product_standard_load_multiple(FALSE, ['product_id' => $p->id]);
      if (!empty($es)) {
        foreach ($es as $e) {
          if ($e instanceof ShusyProductStandard) {
            if ($e->status == 1) {
              return;
            }
          }
        }
      }
      form_error($element, t('必须有已上架的规格,产品才能上架'));
    }
  }
}

function shusy_product_shusy_product_entity_form_submit($form, &$form_state) {
  $e = $form_state[ShusyProduct::class];
  if ($e instanceof ShusyProduct) {
    $isNew = empty($e->id);
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->save();

    $multistandards = $form_state['values']['multistandards']['items'] ?? [];
    foreach ($multistandards as $li => $standard) {
      if (!empty($standard['id'])) {
        $standardEntity = shusy_product_standards_load($standard['id']);
      }
      else {
        $standardEntity = new ShusyProductStandards();
        $standardEntity->product_id = $e->id;
      }
      if ($standardEntity instanceof ShusyProductStandards) {
        $standardEntity->product_id = $e->id;
        $standardEntity->standard = $standard['standard'];
        $standardEntity->status = $standard['status'];
        $standardEntity->save();
      }
    }
    $multistandardsDel = $form_state['multistandardsDel'] ?? [];
    foreach ($multistandardsDel as $item) {
      if ($item instanceof ShusyProductStandards) {
        $item->delete();
      }
    }

    //新建后去上传规格
    if ($isNew) {
      $form_state['redirect'] = "admin/content/shusy_product/{$e->id}/shusy_product_standard";
    }
  }
}

function shusy_product_shusy_product_delete_form($form, &$form_state, ShusyProduct $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProduct::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/shusy_product/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function shusy_product_shusy_product_delete_form_submit($form, &$form_state) {
  $e = $form_state[ShusyProduct::class];
  if ($e instanceof ShusyProduct) {
    $e->delete();
  }
}

function shusy_product_shusy_product_comment_entity_form($form, &$form_state, ShusyProductComment $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProductComment::class] = $e;

  $form['content'] = [
    '#type' => 'textarea',
    '#title' => t('评论内容'),
    '#default_value' => $e->content,
  ];
  $form['score'] = [
    '#type' => 'select',
    '#title' => t('有图'),
    '#options' => $e->getScoreOptions(),
    '#default_value' => $e->score,
    '#chosen' => TRUE,
    '#required' => TRUE,
  ];
  $form['has_img'] = [
    '#type' => 'select',
    '#title' => t('有图'),
    '#options' => $e->getHasImgOptions(),
    '#default_value' => $e->has_img,
    '#chosen' => TRUE,
    '#required' => TRUE,
  ];
  $form['status'] = [
    '#type' => 'select',
    '#title' => t('状态'),
    '#options' => $e->getStatusOptions(),
    '#default_value' => $e->status,
    '#chosen' => TRUE,
    '#required' => TRUE,
  ];

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function shusy_product_shusy_product_comment_entity_form_submit($form, &$form_state) {
  $e = $form_state[ShusyProductComment::class];
  if ($e instanceof ShusyProductComment) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->save();
  }
}

function shusy_product_shusy_product_comment_delete_form($form, &$form_state, ShusyProductComment $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProductComment::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/shusy_product_comment/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function shusy_product_shusy_product_comment_delete_form_submit($form, &$form_state) {
  $e = $form_state[ShusyProductComment::class];
  if ($e instanceof ShusyProductComment) {
    $e->delete();
  }
}

function shusy_product_shusy_product_standard_entity_form($form, &$form_state, ShusyProductStandard $e, ShusyProduct $product, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProductStandard::class] = $e;
  $form_state[ShusyProduct::class] = $product;

  $form['sku'] = [
    '#type' => 'textfield',
    '#title' => t('SKU'),
    '#required' => TRUE,
    '#default_value' => $e->sku,
    '#element_validate' => ['shusy_product_standard_validate_sku'],
  ];
  $form['standard'] = [
    '#type' => 'textfield',
    '#title' => t('规格'),
    '#required' => TRUE,
    '#default_value' => $e->standard,
  ];
  if (module_exists('shusy_product_standards')) {
    $multistandards = shusy_product_standards_load_multiple(FALSE, [
      'product_id' => $product->id,
      'status' => 1,
    ]);
    if (!empty($multistandards)) {
      $form['multistandards'] = [
        '#title' => t('多规格'),
        '#type' => 'fieldset',
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
        '#tree' => TRUE,
      ];
    }
    foreach ($multistandards as $multistandard) {
      if ($multistandard instanceof ShusyProductStandards) {
        $item = shusy_product_standards_items_new_single(FALSE, [
          'standard_id' => $e->id,
          'spstandard_id' => $multistandard->id,
        ]);
        $form['multistandards']["multistandard|" . $multistandard->id] = [
          '#type' => 'textfield',
          '#title' => $multistandard->standard,
          '#required' => TRUE,
          '#default_value' => $item->standard,
        ];
      }
    }
  }
  $form['amount'] = [
    '#type' => 'textfield',
    '#title' => t('价格'),
    '#required' => TRUE,
    '#default_value' => $e->amount / 100,
    '#maxlength' => 8,
    '#size' => 8,
    '#field_suffix' => t('RMB'),
  ];
  $form['cost'] = [
    '#type' => 'textfield',
    '#title' => t('原价'),
    '#required' => TRUE,
    '#default_value' => $e->cost / 100,
    '#maxlength' => 8,
    '#size' => 8,
    '#field_suffix' => t('RMB'),
  ];
  $form['status'] = [
    '#type' => 'checkbox',
    '#title' => t('上架'),
    '#default_value' => $e->status,
  ];

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

//检查SKU SKU不能重复
function shusy_product_standard_validate_sku($element, &$form_state) {
  $e = $form_state[ShusyProductStandard::class];
  if ($e instanceof ShusyProductStandard) {
    $value = $element['#value'];
    $es = shusy_product_standard_load_multiple(FALSE, ['sku' => $value]);
    if (!empty($es)) {
      $skue = reset($es);
      if ($skue instanceof ShusyProductStandard && $e->id != $skue->id) {
        form_error($element, t('SKU必须唯一'));
      }
    }
  }
}

function shusy_product_shusy_product_standard_entity_form_submit($form, &$form_state) {
  $e = $form_state[ShusyProductStandard::class];
  if ($e instanceof ShusyProductStandard) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->amount = ceil($e->amount * 100);
    $e->cost = ceil($e->cost * 100);
    $e->save();

    $multistandards = $form_state['values']['multistandards'] ?? [];
    foreach ($multistandards as $key => $multistandard) {
      [, $mid] = explode("|", $key);
      $item = shusy_product_standards_items_new_single(FALSE, [
        'standard_id' => $e->id,
        'spstandard_id' => $mid,
      ]);
      $item->product_id = $e->product_id;
      $item->standard = $multistandard;
      $item->save();
    }

  }
}

function shusy_product_shusy_product_standard_delete_form($form, &$form_state, ShusyProductStandard $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProductStandard::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/shusy_product_standard/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function shusy_product_shusy_product_standard_delete_form_submit($form, &$form_state) {
  $e = $form_state[ShusyProductStandard::class];
  if ($e instanceof ShusyProductStandard) {
    $e->delete();
  }
}

function shusy_product_shusy_product_entity_form2($form, &$form_state, ShusyProduct $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_product') . '/shusy_product.forms.inc';
  $form_state[ShusyProduct::class] = $e;

  $form['name'] = [
    '#type' => 'textfield',
    '#title' => t('产品标题'),
    '#required' => TRUE,
    '#default_value' => $e->name,
    '#element_validate' => ['shusy_product_validate_title_length'],
  ];
  $form['info'] = [
    '#type' => 'textfield',
    '#title' => t('产品说明'),
    '#required' => TRUE,
    '#default_value' => $e->info,
  ];
  $form['vip'] = [
    '#type' => 'checkbox',
    '#title' => t('允许VIP折扣'),
    '#default_value' => $e->vip,
    '#description' => t('仅当产品属于VIP价格分类时有效'),
  ];
  $form['summary'] = [
    '#type' => 'textarea',
    '#title' => t('摘要介绍'),
    '#default_value' => $e->summary,
  ];

  if (empty($form_state['standards']) && empty($form_state['standardsDel'])) {
    $packages = shusy_product_standard_load_multiple(FALSE, [
      'product_id' => $e->id,
      'status' => [0, 1],
    ]);
    usort($packages, 'shusy_product_sort_weight');
    if (!empty($packages)) {
      $form_state['standards'] = $packages;
    }
    else {
      $form_state['standards'] = [];
    }
  }
  $form['standards'] = [
    '#title' => t('产品规格'),
    '#type' => 'fieldset',
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#tree' => TRUE,
    '#prefix' => "<div id='standards-form-wrapper'>",
    '#suffix' => '</div>',
  ];
  $form['standards']['items'] = [
    '#type' => 'item',
    '#theme' => 'shusy_product_form_standards',
  ];
  $parents = [];
  foreach ($form_state['standards'] as $pi => $standard) {
    if ($standard instanceof ShusyProductStandard) {
      $standardId = "standards-form-wrapper-{$pi}";

      $form['standards']['items'][$pi] = [
        '#type' => 'container',
        '#entity_builders' => ['shusy_product_form_build_entity'],
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi]),
      ];

      $form['standards']['items'][$pi]['id'] = [
        '#type' => 'value',
        '#value' => $standard->id,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['id']),
      ];

      $form['standards']['items'][$pi]['standard'] = [
        '#type' => 'textfield',
        '#title' => t('规格'),
        '#title_display' => 'invisible',
        '#default_value' => $standard->standard,
        '#required' => TRUE,
        '#size' => 32,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['standard']),
      ];
      $form['standards']['items'][$pi]['sku'] = [
        '#type' => 'textfield',
        '#title' => t('SKU'),
        '#title_display' => 'invisible',
        '#element_validate' => ['shusy_product_validate_sku'],
        '#default_value' => $standard->sku,
        '#required' => TRUE,
        '#size' => 16,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['sku']),
      ];
      $form['standards']['items'][$pi]['amount'] = [
        '#type' => 'textfield',
        '#title' => t('价格'),
        '#title_display' => 'invisible',
        '#element_validate' => ['element_validate_number'],
        '#default_value' => $standard->amount / 100,
        '#required' => TRUE,
        '#size' => 4,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['amount']),
      ];
      $form['standards']['items'][$pi]['weight'] = [
        '#type' => 'textfield',
        '#size' => 4,
        '#maxlength' => 32,
        '#element_validate' => ['element_validate_number'],
        '#title' => t('净重克'),
        '#title_display' => 'invisible',
        '#default_value' => $standard->weight(),
        '#required' => TRUE,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['weight']),
      ];
      $form['standards']['items'][$pi]['cost'] = [
        '#type' => 'textfield',
        '#title' => t('成本'),
        '#title_display' => 'invisible',
        '#element_validate' => ['element_validate_number'],
        '#default_value' => $standard->cost / 100,
        '#required' => TRUE,
        '#size' => 4,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['cost']),
      ];
      $form['standards']['items'][$pi]['stock'] = [
        '#type' => 'textfield',
        '#title' => t('库存'),
        '#title_display' => 'invisible',
        '#element_validate' => ['element_validate_number'],
        '#default_value' => $standard->stock(),
        '#required' => TRUE,
        '#size' => 4,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['stock']),
      ];
      $form['standards']['items'][$pi]['status'] = [
        '#type' => 'checkbox',
        '#title' => t('启用'),
        '#title_display' => 'invisible',
        '#default_value' => $standard->status,
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['status']),
      ];
      $form['standards']['items'][$pi]['delete'] = [
        '#type' => 'submit',
        '#value' => t('删除'),
        '#submit' => ['shusy_product_form_standards_remove_submit'],
        '#name' => "$standardId-op-del",
        '#limit_validation_errors' => [],
        '#ajax' => [
          'callback' => 'shusy_product_form_standards_callback',
          'wrapper' => 'standards-form-wrapper',
        ],
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['delete']),
      ];

      $form['standards']['items'][$pi]['sort'] = [
        '#type' => 'weight',
        '#title' => t('Weight'),
        '#default_value' => $standard->sort,
        '#delta' => 50,
        '#title_display' => 'invisible',
        '#parents' => array_merge($parents, ['standards'], ['items'], [$pi], ['sort']),
      ];

      $tmp = $form['standards']['items'][$pi];
      field_attach_form($standard->entityType(), $standard, $tmp, $form_state);
      $form['standards']['items'][$pi] = $tmp;

    }
  }
  $form['standards']['add'] = [
    '#type' => 'submit',
    '#value' => t('添加规格'),
    '#submit' => ['shusy_product_form_standards_add_submit'],
    '#limit_validation_errors' => [],
    '#ajax' => [
      'callback' => 'shusy_product_form_standards_callback',
      'wrapper' => 'standards-form-wrapper',
    ],
  ];

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

/**
 * @param $element
 * @param $form_state
 * 验证SKU唯一
 */
function shusy_product_validate_sku($element, &$form_state) {
  $value = $element['#value'];
  [, , $pi] = $element['#array_parents'];
  $standard = $form_state['standards'][$pi];
  $items = $form_state['values']['standards']['items'];
  $skus = [];
  foreach ($items as $i => $item) {
    if ($pi != $i) {
      $skus[] = $item['sku'];
    }
  }
  //如果在列表中
  if (in_array($value, $skus)) {
    form_error($element, t('SKU 必须唯一.', ['%name' => $element['#title']]));
  }
  //检查是否在数据库 其它产品中
  $es = shusy_product_standard_load_multiple(FALSE, [
    'sku' => $value,
    'status' => [0, 1],
  ]);
  if (!empty($es)) {
    $e = reset($es);
    if ($e instanceof ShusyProductStandard && $standard instanceof ShusyProductStandard && $e->id != $standard->id) {
      form_error($element, t('SKU 必须唯一.', ['%name' => $element['#title']]));
    }
  }
}

function theme_shusy_product_form_standards($variables) {
  $output = '';
  $form = $variables['form'];
  $rows = [];

  foreach (element_children($form) as $id) {
    $form[$id]['sort']['#attributes']['class'] = ['item-weight'];
    $rows[] = [
      'data' => [
        drupal_render($form[$id]['sku']),
        drupal_render($form[$id]['sort']),
        drupal_render($form[$id]['field_image']),
        drupal_render($form[$id]['standard']),
        drupal_render($form[$id]['cost']),
        drupal_render($form[$id]['amount']),
        drupal_render($form[$id]['weight']),
        drupal_render($form[$id]['stock']),
        drupal_render($form[$id]['status']),
        drupal_render($form[$id]['delete']),
      ],
      'class' => ['draggable'],
    ];
  }
  $header = [
    t('SKU'),
    t('Weight'),
    t('规格图片'),
    t('规格'),
    t('成本:RMB'),
    t('售价:RMB'),
    t('净重:克'),
    t('库存'),
    t('上架'),
    t('操作'),
  ];

  $table_id = 'items-table';
  $form['items_markup']['markup']['#markup'] = theme('table', [
    'header' => $header,
    'rows' => $rows,
    'attributes' => ['id' => $table_id],
  ]);
  $output .= drupal_render_children($form);
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'item-weight');
  return $output;
}

function shusy_product_form_standards_add_submit($form, &$form_state) {
  $form_state['standards'][] = new ShusyProductStandard();
  $form_state['rebuild'] = TRUE;
}

function shusy_product_form_standards_remove_submit($form, &$form_state) {
  [, , $li] = $form_state['triggering_element']['#array_parents'];
  $item = $form_state['standards'][$li];
  $form_state['standardsDel'][] = $item;
  unset($form_state['standards'][$li]);
  $form_state['rebuild'] = TRUE;
}

function shusy_product_form_standards_callback($form, &$form_state) {
  return $form['standards'];
}

function shusy_product_shusy_product_entity_form2_submit($form, &$form_state) {
  $e = $form_state[ShusyProduct::class];
  if ($e instanceof ShusyProduct) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->save();

    $standards = $form_state['values']['standards']['items'] ?? [];
    foreach ($standards as $li => $standard) {
      if (!empty($standard['id'])) {
        $standardEntity = shusy_product_standard_load($standard['id']);
      }
      else {
        $standardEntity = new ShusyProductStandard();
        $standardEntity->product_id = $e->id;
      }
      if ($standardEntity instanceof ShusyProductStandard) {
        $standardEntityForm = $form['standards']['items'][$li];
        entity_form_submit_build_entity($standardEntity->entityType(), $standardEntity, $standardEntityForm, $form_state);
        $standardEntity->cost = bcmul($standardEntity->cost, 100);
        $standardEntity->amount = bcmul($standardEntity->amount, 100);
        $standardEntity->save();
        //库存记录
        shusy_product_stock_set($standardEntity, $standard['stock']);
        shusy_product_weight_set($standardEntity, $standard['weight']);
      }
    }

    $standardsDel = $form_state['standardsDel'] ?? [];
    foreach ($standardsDel as $item) {
      if ($item instanceof ShusyProductStandard) {
        $item->delete();
      }
    }

    $standards = shusy_product_standard_load_multiple(FALSE, [
      'product_id' => $e->id,
      'status' => 1,
    ]);
    //没有上架的规格 产品自动下架
    if (empty($standards) && $e->status == 1) {
      $e->status = 0;
      $e->save();
    }
    //关联主规格
    if (!empty($standards)) {
      usort($standards, 'shusy_product_sort_weight');
      $standardTmp = reset($standards);
      if ($standardTmp instanceof ShusyProductStandard) {
        $e->standard_id = $standardTmp->id;
        $e->save();
      }
    }

  }
}
